import axios from "axios";
import baseURL from "../config/env";
import { useStore } from "../store";
import Cookies from "js-cookie";
import { ElMessage, ElLoading } from "element-plus";
const contentType = {
  json: "application/json;charset=utf-8",
  form: "application/x-www-form-urlencoded;charset=utf-8",
};

const statusMap = {
  400: "请求错误",
  401: "未授权，请登录",
  403: "拒绝访问",
  404: "请求地址出错",
  405: "方法不被允许",
  408: "请求超时",
  500: "服务器内部错误",
  501: "服务未实现",
  502: "网关错误",
  503: "服务不可用",
  504: "网关超时",
  505: "HTTP版本不受支持",
};
axios.defaults.timeout = 1000000;
axios.defaults.withCredentials = true;
const jsonInstance = axios.create({
  baseURL: "",
  headers: {
    post: {
      "Content-Type": contentType.json,
    },
    delete: {
      "Content-Type": contentType.json,
    },
    put: {
      "Content-Type": contentType.json,
    },
  },
});

const formInstance = axios.create({
  baseURL: "",
  headers: {
    post: {
      "Content-Type": contentType.form,
    },
    delete: {
      "Content-Type": contentType.form,
    },
    put: {
      "Content-Type": contentType.form,
    },
  },
});

[jsonInstance, formInstance].forEach((instance, index) => {
  instance.interceptors.request.use(
    (config) => {
      let store = useStore();
      store.$patch((state) => {
        state.apiLoading = true;
      });
      let javaType = config[0] || config.params.java;
      config.baseURL = baseURL[javaType];
      if (config.method === "get") {
        const t = new Date().getTime();
        config.url += config.url.includes("?") ? `&t=${t}` : `?t=${t}`;
      }
      if (store.token) {
        config.headers.Authorization = store.token;
      }

      if (index === 1) {
        console.log(config);
        //post 请求参数在data里面   get请求参数在params里面（默认就是form表单格式）   post 的参数要格式化成表单格式
        config.data = qs.stringify({
          ...config.data,
          allowDots: true,
        });
      }

      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
});

[jsonInstance, formInstance].forEach((instance) => {
  instance.interceptors.response.use(
    (response) => {
      let store = useStore();
      store.$patch((state) => {
        state.apiLoading = false;
      });
      if (response.data.code == 401) {
        const ua = window.navigator.userAgent;
        //登录失效，状态码根据情况修改
        Cookies.remove("session", {
          expires: "",
          path: "",
          domain: ".ahggwl.com", //根据情况修改
          secure: false,
        });
        store.$reset();
        ElMessage.error("登录失效，请重新登录！");
        window.location.href = ""; //跳转登录页面
      } else {
        return response.data;
      }
    },
    (error) => {
      store.$patch((state) => {
        state.apiLoading = false;
      });
      if (error.message.includes("timeout")) {
        ElMessage.error(`请求超时,请稍后重试或者联系管理员！<br>${error.message}`);
      }
      return Promise.reject(error.response);
    }
  );
});
export const jsonAxios = jsonInstance;
export const formAxios = formInstance;
